package com.dek.rabbitmq.demo;

import com.dek.rabbitmq.commons.Constants;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitProducer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.IP_ADDRESS);
        factory.setPort(Constants.PORT);
        factory.setUsername("guest");
        factory.setPassword("guest");

        try( Connection connection = factory.newConnection();
             //创建信道
        Channel channel = connection.createChannel()) {
            // 创建一个 type="direct" 、持久化的、非自动删除的交换器
            channel.exchangeDeclare(Constants.EXCHANGE_NAME, "direct" , true , false , null) ;
            //创建一个持久化、非排他的、非自动删除的队列
            channel. queueDeclare(Constants.QUEUE_NAME, true, false , false , null) ;
            //将交换器与队列通过路由键绑定
            channel.queueBind(Constants.QUEUE_NAME , Constants.EXCHANGE_NAME , Constants.ROUTING_KEY);
            //发送一条持久化的消息: hello world !
            String message = "Hello World !";
            channel.basicPublish(Constants.EXCHANGE_NAME, Constants.ROUTING_KEY ,
                    MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes()) ;

            //关闭资源
//        channel.close() ;
//        connection.close();
        }
    }

}
